//
//  DevParamsAlertController.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/25.
//

#import "DevParamsAlertController.h"
#import "RHWindowTipManage.h"
#import "DeviceChartItemView.h"
#import "DeviceChartFieldModel.h"
#import "NSString+LenWid.h"
#import "DevChartModel.h"

@interface DevParamsAlertController ()

@property (nonatomic ,strong) DevChartModel *model;

@property (nonatomic ,assign) BOOL isFull;

@property (nonatomic ,strong) NSMutableArray *selectArray;

//参数选择的最大个数 默认6个
@property (nonatomic, assign) NSInteger maxSelectCount;
@end

@implementation DevParamsAlertController

- (instancetype)initWithModel:(DevChartModel *)chartModel isFull:(BOOL)isFull{
    self = [super init];
    if (self) {
        self.isFull = isFull;
        self.model = chartModel;
        self.maxSelectCount = 6;
    }
    
    return self;
}
- (instancetype)initWithModel:(DevChartModel *)chartModel isFull:(BOOL)isFull maxSelectCount:(NSInteger)maxSelectCount{
    self = [super init];
    if (self) {
        self.isFull = isFull;
        self.model = chartModel;
        self.maxSelectCount = maxSelectCount;
    }
    
    return self;
}

- (NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}


- (void)setModel:(DevChartModel *)model{
    _model = model;
    [_model.selectArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartFieldModel *field_model = obj;
        [self.selectArray addObject:field_model.keyCode];
    }];
    
    [_model.params enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull field_model, NSUInteger idx, BOOL * _Nonnull stop) {

        if ([self.selectArray containsObject:field_model.keyCode]) {
            field_model.isShowLine = YES;
        }else{
            field_model.isShowLine = NO;
        }
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.3]];
    
    UIView *touchView = [[UIView alloc] init];
    [touchView setBackgroundColor:UIColor.clearColor];
    [self.view addSubview:touchView];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    touchView.userInteractionEnabled = YES;
    [touchView addGestureRecognizer:tap];
    
    UIView *boxView = [[UIView alloc] init];
    [boxView setBackgroundColor:UIColor.whiteColor];
    [boxView.layer setCornerRadius:9];
    [boxView shadow:UIColor.blackColor opacity:0.1 radius:5 offset:CGSizeMake(0, 1)];
    [self.view addSubview:boxView];
    
    
    QMUILabel *lab = [[QMUILabel alloc] init];
    [lab setText:@"参数".rh_localized];
    [lab setTextAlignment:NSTextAlignmentLeft];
    [lab setFont:[UIFont systemFontOfSize:16]];
    [lab setTextColor:FontColor(@"#242424")];
    [boxView addSubview:lab];
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:FontColor(@"#F5F5F5")];
    [boxView addSubview:lineV];
    
    
    UIScrollView *scroll = [[UIScrollView alloc] init];
    [boxView addSubview:scroll];
    scroll.backgroundColor = [UIColor whiteColor];
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor whiteColor];
    [scroll addSubview:contentView];
    
    __block DeviceChartItemView *lastItemV;
    __block CGFloat lastX;
    kWeakSelf;
    [self.model.params enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat item_width;
        DeviceChartFieldModel *fieldModel = obj;
        fieldModel.colorStr = @"#000000";
        DeviceChartItemView *itemView = [[DeviceChartItemView alloc] init];
        //从后台获取的数据可能没有这字段
        if(fieldModel.alias.length == 0){
            fieldModel.alias = fieldModel.keyName;
        }
        [itemView setModel:fieldModel];
        [contentView addSubview:itemView];
        CGSize size = [NSString getStringSizeWith:fieldModel.keyName withStringFont:10 withWidthOrHeight:20 isWidthFixed:NO];
        item_width = size.width+10+5+10+5;
        if (!lastItemV) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(item_width);
                make.top.mas_offset(5);
                make.left.mas_offset(0);
                make.height.mas_equalTo(20);
            }];
            lastX = item_width+5;
        }else{
            if ((lastX+item_width)>(self.isFull?335-40:(kUI_WINDOW_W-60-40))) {
                lastX = 0;
            }
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(item_width);
                make.left.mas_offset(lastX);
                make.height.mas_equalTo(20);
                if (lastX == 0) {
                    make.top.equalTo(lastItemV.mas_bottom).offset(15);
                }else{
                    make.centerY.equalTo(lastItemV);
                }
            }];

            lastX = lastX+item_width+5;
        }
        
        itemView.selectBlock = ^BOOL(DeviceChartFieldModel * _Nonnull model) {
            return [weakSelf itemSelectActin:model];
        };
        lastItemV = itemView;
    }];
    
    [lastItemV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-15);
    }];
    
    
    NSArray *titles = @[@"取消".rh_localized,@"确认".rh_localized];
    NSMutableArray *array = [NSMutableArray array];

    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitleColor:FontColor(idx == 0 ? @"#000000":@"#ffffff") forState:UIControlStateNormal];
        [btn setBackgroundColor:FontColor(idx == 0 ? @"#eeeeee":@"#56C271")];
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn.layer setCornerRadius:9];
        [boxView addSubview:btn];
        [array addObject:btn];
        
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (idx == 0) {
                [weakSelf hidden];
            }else{
                [weakSelf confirmAction];
            }
        }];
    }];
    
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.top.mas_offset(20);
        make.height.mas_equalTo(18);
    }];
    
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(lab.mas_bottom).offset(20);
        make.height.mas_equalTo(2);
    }];
    
    [scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(lab);
        make.top.equalTo(lineV).offset(5);
        make.bottom.mas_offset(-60);
    }];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(scroll);
        make.width.mas_equalTo(scroll);
        make.height.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-15);
        make.height.mas_equalTo(40);
    }];
    
    [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:100 leadSpacing:15 tailSpacing:15];
    
    
    if (self.isFull) {
        [boxView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_offset(0);
            make.size.mas_equalTo(CGSizeMake(335,285));
        }];
    }else{
        [boxView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_offset(0);
            make.size.mas_equalTo(CGSizeMake(kUI_WINDOW_W-60, (kUI_WINDOW_W-60)*285/335));
        }];
    }
    
    [touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

    
    [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [weakSelf hidden];
    }];
    
}

#pragma amrk - Action
- (BOOL)itemSelectActin:(DeviceChartFieldModel *)model{
    //勾选的时候判断一下
    if ((self.selectArray.count >= self.maxSelectCount) &&!model.isShowLine) {
        [ProgressHUDManage showInfo:[NSString stringWithFormat:@"%@%ld %@",@"最多只能选择".rh_localized,self.maxSelectCount,@"个".rh_localized]];
        return NO;
    }
    
    if (model.isShowLine) {
        [self.selectArray removeObject:model.keyCode];
    }else{
        [self.selectArray addObject:model.keyCode];
    }
    model.isShowLine = !model.isShowLine;
    
    return YES;
}


- (void)confirmAction{
    
    NSMutableArray *array = [NSMutableArray array];
    [self.model.params enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartFieldModel *field_model = obj;
        if ([self.selectArray containsObject:field_model.keyCode]) {
            DeviceChartFieldModel *model = [DeviceChartFieldModel yy_modelWithDictionary:[field_model yy_modelToJSONObject]];
            model.isShowLine = YES;
            [array addObject:model];
        }
    }];
    
    self.model.selectArray = array;
    
    if (self.resultBlock) {
        self.resultBlock();
    }
    
    [self hidden];
}

- (void)hidden{
    [self dismissViewControllerAnimated:NO completion:nil];
    [[RHWindowTipManage shareWindowTipManage] hidden];
}

@end
